package com.yc.bbs.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Component
@ServerEndpoint("/talk/{id}")
public class TalkDo {
    //websocket会为每个连接成功客户端创建一个talkdo对象
    //在线用户容器
    private static Map<String, Session> onlines = new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        session.getUserProperties().put("id", id);
        onlines.put(id, session);
        String json=bulidMsg(id,"上线了",true);
        sendMessage(json);
    }

    @OnClose
    public void onClose(Session session) {
        Object id = session.getUserProperties().get("id");
        onlines.remove(id);
        String json=bulidMsg((String) id,"下线了",true);
        sendMessage(json);
    }
    @OnError
    public void onErro(Session session, Throwable throwable) {
        System.out.println("异常"+throwable.getMessage());
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        Object id = session.getUserProperties().get("id");
        String json=bulidMsg((String) id,message,true);
        sendMessage(json);
    }
    public  void sendMessage(String message){
        onlines.values().forEach(session -> {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
    ObjectMapper objectMapper=new ObjectMapper();
    public String bulidMsg(String author, String content,boolean isOnlinex){
        Msg msg=new Msg(author,content,null);
        if(isOnlinex){
            List<Object> onlinesId= onlines.values().
                    stream()
                    .map(session -> session.getUserProperties().get("id"))
                    .collect(Collectors.toList());
            msg.onlnes=onlinesId;
        }
        try {
            return objectMapper.writeValueAsString(msg);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("转换消息出错",e);
        }
    }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Msg{
    //谁发的
    String author;
    //内容
    String content;
    //在线人数列表
    List<Object> onlnes;
}
